package com.android.bookgarden.tabfragment;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.bookgarden.MainActivity;
import com.android.bookgarden.R;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseFragment;
import com.android.bookgarden.bean.BtItem;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.db.XutilsDataDao;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.ui.MyInterestActivity;
import com.android.bookgarden.ui.SearchActivity;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.PagerSlidingTabStrip;
import com.lzy.okgo.model.HttpHeaders;
import com.uuzuche.lib_zxing.activity.QRCodeActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.Unbinder;

/**
 * @author XLC
 * @description 首页布局(正式使用时去掉Test前缀)
 * @time 2018-11-28
 */
public class TestIndexFragment extends BaseFragment implements RealtConstract.View {

    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;

    public List<BtItem> item;
    @BindView(R.id.myInterest)
    ImageView myInterest;
    Unbinder unbinder;
    private MyPagerAdapter mAdapter;
    @BindView(R.id.view_pager)
    ViewPager mPager;
    @BindView(R.id.tab_layout)
    PagerSlidingTabStrip mStrip;
    @BindView(R.id.scanBut)
    ImageView scanBut;
    private XutilsDataDao dataDao;
    private RealtConstract.Presenter presenter;
    private List<BtItem> btItems;
    public static TestIndexFragment testIndexFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.index_fragment;
    }

    @Override
    protected void initView() {
        testIndexFragment = this;
        searchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(SearchActivity.class);
            }
        });
        dataDao = XutilsDataDao.getInstance(getActivity());
        btItems = dataDao.queryAll(BtItem.class);
        presenter = new BasePersenter(this, getActivity());
        getData();

        myInterest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utlis.isLogin(getActivity())) {
                    return;
                }
//                Intent intent = new Intent(getActivity(),MyInterestActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("item", (Serializable) item);

                startActivity(MyInterestActivity.class);
            }
        });
        scanBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(QRCodeActivity.class);
            }
        });
    }

    public void init() {
        btItems = dataDao.queryAll(BtItem.class);
        item.clear();
        mAdapter.notifyDataSetChanged();
        getData();
    }


    private void getData() {
        HttpHeaders headers = new HttpHeaders();
        headers.put("token", MainActivity.mainActivity.token);
        presenter.loadDataHeader(null, "", Apis.GET_XQ, 1001, headers, HttpType.GET);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void returnData(String data, int urlCode) {
        LogUtil.e("返回数据", data + "");
        if (TextUtils.isEmpty(data)) {
            return;
        }

        handler.obtainMessage(urlCode, data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {

    }

    public class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return item.get(position).getName();
        }

        @Override
        public int getCount() {
            return item.size();
        }

        @Override
        public Fragment getItem(int position) {
            HomeTabFragment homeTabFragment = HomeTabFragment.newInstance(position, item.get(position).getId());
//            Bundle data = new Bundle();
//            data.putString("url", item.get(position).getUrl());
//            homeTabFragment.setArguments(data);
            return homeTabFragment;
        }

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            switch (msg.what) {
                case 1001:
                    try {
                        getType(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    private void getType(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        int code = object.getInt("code");
        if (code == 200) {
            List<BtItem> list = JsonUitl.stringToList(object.getString("data"), BtItem.class);
            if (null != list && list.size() > 0) {
                item = new ArrayList<>();
                if (null != btItems && btItems.size() > 0) {
                    dataDao.deleteTable(BtItem.class);
                    List<BtItem> bs = Utlis.removeDuplicate(btItems, list);
                    item.addAll(bs);
                } else {
                    item.addAll(list);
                }
                dataDao.insert(item);
                for (int i = 0; i < item.size(); i++) {
                    if (!item.get(i).isShow()) {
                        item.remove(i);
                    }
                }
                mAdapter = new MyPagerAdapter(getChildFragmentManager());
                mPager.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                mStrip.setTabTextColor(Color.parseColor("#FF000000"));
                mStrip.setIsSelectBold(true);
                mStrip.setSelectedTabTextSize(18);
                mStrip.setSelectedTabTextColor(Color.parseColor("#FF000000"));
                mStrip.setViewPager(mPager);
            }

        }
    }


}
